package com.my.sender;

import com.my.util.MailUtil;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.concurrent.TimeUnit;

@Component
@RabbitListener(
        bindings = @QueueBinding(
                value = @Queue(value = "${mq.config.queue.email.push}", autoDelete = "true"),
                exchange = @Exchange(value = "${mq.config.email.exchange}", type = ExchangeTypes.FANOUT)
        )
)
public class MailSender {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 接收消息的方法，采用消息队列监听机制
     *
     * @param email
     */
    @RabbitHandler
    public void process(String email) {
        try {
            MailUtil.send_mail(email);
            System.out.println("Business-Email-Sender:" + MailUtil.getCode());
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(new StringRedisSerializer());
            redisTemplate.opsForValue().set("business" + email, MailUtil.getCode(), 5, TimeUnit.MINUTES);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
